import { configStore } from "@/store/configStore";
import type { DeviceInfo, DeviceResponse, ProductSimpleResponse } from "./type/interface";
import { getConfig } from "@/api/interface/interface";
import { getCurrentInstance, ref } from "vue";

/**
 * 设置或者读取token
 * @returns string
 */
export const token = (value: string = "") => {
    return value === "" ? uni.getStorageSync("token") : uni.setStorageSync("token", value);
}


/**
 * 判断是否已经登录
 * @returns boolean
 */
export const isLogin = () => {
    return !!token();
}

/**
 * 设置或者读取spread_uid
 * @returns string
 */
export const spreadUid = (value: string = "") => {
    return value === "" ? uni.getStorageSync("spread_uid") : uni.setStorageSync("spread_uid", value);
}


/**
 * 设置或者读取user_sn
 * @returns string
 */
export const userSn = (value: string = "") => {
    return value === "" ? uni.getStorageSync("user_sn") : uni.setStorageSync("user_sn", value);
}

/**
 * 节流函数
 */
type Procedure = (...args: any[]) => void;
export const throttle = (fn: Procedure, delay: number): Procedure => {
    let lastTime = 0;
    return function (this: any, ...args: any[]) {
        const now = Date.now();
        if (now - lastTime >= delay) {
            lastTime = now;
            fn.apply(this, args);
        }
    };
};

/**
 * 防抖函数
 */
export const debounce = (fn: Procedure, delay: number) => {
    let timeout: number;
    return function (this: any, ...args: any[]) {
        clearTimeout(timeout);
        timeout = setTimeout(() => fn.apply(this, args), delay);
    };
}

export const toProductDetail = (item: ProductSimpleResponse | undefined) => {
    let url = `/pages/index/detail?id=${item?.device_ids}-${item?.id}`;
    if (!isLogin()) {
        url = "/pages/login/login";
    }
    uni.navigateTo({ url });
    return;
}


export const getAppConfig = () => {
    getConfig().then(res => {
        const { setApp } = configStore();
        setApp(res.data);
    })
}


export const setJssdk = ({ jssdk, wechat_share_title, wechat_share_desc, wechat_share_image }: any, instance: any) => {
    if (jssdk === undefined) {
        //return;
    }
    jssdk.openTagList = ['wx-open-launch-weapp'];
    const self: any = instance?.appContext.config.globalProperties;

    self.$wx.config(jssdk);

    const shareObj = {
        title: wechat_share_title, // 分享标题
        desc: wechat_share_desc, // 分享描述
        link: `${import.meta.env.VITE_BASE_URL}/wechat_h5`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: wechat_share_image, // 分享图标
        success: function (res: any) {
            console.log("updateTimelineShareData success", res);
        },
        fail(error: any) {
            console.log("updateTimelineShareData fail", error);
        }
    }
    self.$wx.ready(function () {      //需在用户可能点击分享按钮前就先调用\
        self.$wx.updateAppMessageShareData(shareObj);
        self.$wx.updateTimelineShareData(shareObj);
    });
}

